import { Inject, Provide } from '@midwayjs/core';
import { Context } from '@midwayjs/koa';
import { DropsEntity } from '@entity/jx3/drops.entity';
import {
  ListDropsDTO,
  CreateDropsDTO,
  UpdateDropsDTO,
} from '@dto/jx3/drops.dto';
import { resBuild } from '@utils/resBuild';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { JwtService } from '@midwayjs/jwt';
import { getTimeFormat, getUUID } from '@utils';
import { UserService } from '@service/system/user.service';
import { ListUserDTO } from '@dto/system/user.dto';

@Provide()
export class DropsService {
  @Inject()
  ctx: Context;

  @InjectEntityModel(DropsEntity)
  DropsEntity: Repository<DropsEntity>;

  @Inject()
  jwtService: JwtService;

  @Inject()
  userService: UserService;

  async getUserId() {
    // 从请求头或请求参数中获取token
    const token = this.ctx.headers.authorization?.split(' ')[1]; // 假设token在Authorization头中，格式为Bearer <token>
    const decoded: any = await this.jwtService.verify(token, {
      complete: true,
    });
    return decoded.payload.userId;
  }

  // 列表
  async list(queryParams: ListDropsDTO) {
    const queryBuilder = this.DropsEntity.createQueryBuilder('entity');

    // 添加按创建时间排序，默认降序（最新的在前）
    queryBuilder.orderBy('entity.createTime', 'DESC');

    if (queryParams.pageNum && queryParams.pageSize) {
      queryBuilder
        .skip((queryParams.pageNum - 1) * queryParams.pageSize)
        .take(queryParams.pageSize);
    }

    if (queryParams.recordId) {
      queryBuilder.andWhere(`entity.recordId = "${queryParams.recordId}"`);
    }

    const [rows, total] = await queryBuilder.getManyAndCount();
    return resBuild.list(rows, total);
  }

  // 添加
  async create(Drops: CreateDropsDTO) {
    return new Promise(async resolve => {
      // 新增
      Drops.userId = await this.getUserId();
      Drops.id = getUUID();
      const myEntity = this.DropsEntity.create(Drops);
      const { userInfo }: { userInfo: ListUserDTO } =
        await this.userService.userInfo();
      myEntity.setCreateBy(userInfo.nickName);
      myEntity.setUpdateBy(userInfo.nickName);
      myEntity.setCreateTime(getTimeFormat());
      myEntity.setUpdateTime(getTimeFormat());
      await this.DropsEntity.save(myEntity);
      resolve(1);
      return;
    });
  }

  // 删除
  async delete(id: string) {
    const ids = id.split(',').map(id => Number(id));
    await this.DropsEntity.delete(ids);
    return resBuild.success();
  }

  // 修改
  async update(Drops: UpdateDropsDTO) {
    const myEntity = this.DropsEntity.create(Drops);
    const userInfo: ListUserDTO = await this.userService.userInfo();
    myEntity.setUpdateBy(userInfo.nickName);
    myEntity.setUpdateTime(getTimeFormat());
    await this.DropsEntity.save(myEntity);
    return resBuild.success();
  }

  // 详情
  async detail(id: string) {
    const detailInfo = await this.DropsEntity.findOneBy({
      id,
    });
    return resBuild.data(detailInfo);
  }
}
